package com.ler.yrmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.ler.yrmall.search.config.ElasticsearchConf;
import com.ler.yrmall.search.constant.Constant;
import com.ler.yrmall.search.dto.SearchResultDTO;
import com.ler.yrmall.search.dto.SkuEsModelDTO;
import com.ler.yrmall.search.request.SpuSearchRequest;
import com.ler.yrmall.search.service.SpuSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author leron
 */
@Slf4j
@Service
public class SpuSearchServiceImpl implements SpuSearchService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public SearchResultDTO search(SpuSearchRequest searchParamVO) {
        SearchResultDTO result = null;
        //1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParamVO);
        try {
            //2、执行检索请求
            SearchResponse response = client.search(searchRequest, ElasticsearchConf.COMMON_OPTIONS);
            //3、分析响应数据封装成我们需要的格式
            result = buildSearchResult(response, searchParamVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    private SearchRequest buildSearchRequest(SpuSearchRequest request) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(request.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("name", request.getKeyword()));
        }
        if (request.getCategoryId() != null) {
            boolQuery.filter(QueryBuilders.termQuery("categoryId", request.getCategoryId()));
        }
        if (request.getBrandIds() != null && request.getBrandIds().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", request.getBrandIds()));
        }
        if (request.getAttrs() != null && request.getAttrs().size() > 0) {
            for (SpuSearchRequest.Attr attr : request.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attr.getAttrId()));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attr.getAttrValues()));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }
        if (request.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", request.getHasStock() == 1));
        }

        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");

        if (request.getSkuMinPrice() != null) {
            rangeQuery.gte(request.getSkuMinPrice());
        }

        if (request.getSkuMaxPrice() != null) {
            rangeQuery.lte(request.getSkuMaxPrice());
        }

        if (request.getSkuMinPrice() != null || request.getSkuMaxPrice() != null) {
            boolQuery.filter(rangeQuery);
        }

        sourceBuilder.query(boolQuery);

        if (request.getSort() != null) {
            SortOrder order = SpuSearchRequest.Sort.ASC.equals(request.getSort().getMode()) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(request.getSort().getField(), order);
        }
        sourceBuilder.from((request.getPageNo() - 1) * Constant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(Constant.PRODUCT_PAGE_SIZE);

        //2.3、高亮
        if (!StringUtils.isEmpty(request.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("name");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        // 聚合
        //1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);

        //2、分类聚合
        TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("category_agg").field("categoryId").size(20);
        categoryAgg.subAggregation(AggregationBuilders.terms("category_name_agg").field("categoryName").size(1));
        sourceBuilder.aggregation(categoryAgg);
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");

        // attr聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);
        log.info("DSL:{}",sourceBuilder);

        return new SearchRequest(new String[]{Constant.PRODUCT_INDEX}, sourceBuilder);
    }

    /**
     * 构建结果数据
     * @param response
     * @return
     */
    private SearchResultDTO buildSearchResult(SearchResponse response, SpuSearchRequest request) {
        SearchResultDTO result = new SearchResultDTO();
        //1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModelDTO> esModels = new ArrayList<>();
        if (hits.getHits() != null) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModelDTO esModel = JSON.parseObject(sourceAsString, SkuEsModelDTO.class);
                if (!StringUtils.isEmpty(request.getKeyword())) {
                    HighlightField skuName = hit.getHighlightFields().get("name");
                    String string = skuName.getFragments()[0].string();
                    esModel.setName(string);
                }
                esModels.add(esModel);
            }
        }
        result.setSkuList(esModels);


        //当前所有商品涉及到的所有属性信息
        List<SearchResultDTO.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResultDTO.AttrVo attrVo = new SearchResultDTO.AttrVo();
            //1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();

            //3、得到属性的所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }


        result.setAttrs(attrVos);
        //3、当前所有商品涉及到的所有品牌信息
        List<SearchResultDTO.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResultDTO.BrandVo brandVo = new SearchResultDTO.BrandVo();
            //1、得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            //2、得到品牌的名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3、得到品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);
//        //4、当前所有商品涉及到的所有分类信息
        ParsedLongTerms categoryAgg = response.getAggregations().get("category_agg");
        List<SearchResultDTO.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = categoryAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResultDTO.CatalogVo catalogVo = new SearchResultDTO.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCategoryId(Long.parseLong(keyAsString));

            //得到分类名
            ParsedStringTerms categoryNameAgg = bucket.getAggregations().get("category_name_agg");
            String categoryName = categoryNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCategoryName(categoryName);
            catalogVos.add(catalogVo);
        }
        result.setCategory(catalogVos);


        result.setPageNum(request.getPageNo());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalPages = (int) total % Constant.PRODUCT_PAGE_SIZE == 0 ? (int) total / Constant.PRODUCT_PAGE_SIZE : ((int) total / Constant.PRODUCT_PAGE_SIZE + 1);
        result.setTotalPages(totalPages);
        return result;
    }

}
